package com.only4play.web.resource;

import com.only4play.common.model.GeneralResponse;
import com.only4play.common.utils.HttpResponseUtils;
import com.only4play.dto.AssetResourceUploadDto;
import com.only4play.model.entity.AssetResourceEntity;
import com.only4play.service.AssetResourceService;
import com.only4play.vo.AssetResourceDownloadVo;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Path;
import java.util.Objects;

/**
 * @author liyuncong
 * @version 1.0
 * @file AssetResource
 * @brief AssetResource
 * @details AssetResource
 * @date 2023-12-22
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2023-12-22               liyuncong          Created
 */

@RestController
@RequestMapping(path = "/resources", produces = {MediaType.APPLICATION_JSON_VALUE})
public class AssetResResource {

    @Autowired
    private AssetResourceService assetResourceService;

    @PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public GeneralResponse<String> upload(AssetResourceUploadDto uploadDto) {
        return GeneralResponse.of(assetResourceService.upload(uploadDto));
    }

    @GetMapping("/download/{resourceId}")
    public ResponseEntity<InputStreamResource> download(
        @PathVariable("resourceId") Long resourceId
    ) {
        AssetResourceDownloadVo vo = assetResourceService.download(resourceId);
        if (Objects.isNull(vo) || Objects.isNull(vo.getResource())) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .build();
        }
        return HttpResponseUtils.sendAttachment(vo.getResourceName(), vo.getMimeType(), vo.getResource());
    }
}
